package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.cangchu.domain.TZhgdPersonAttnH;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.tool.PlatformTools;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.TZhgdDeviceToolsInfo;
import com.ruoyi.system.domain.TZhgdDeviceToolsStorage;
import com.ruoyi.system.mapper.TZhgdDeviceToolsStorageMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TZhgdDeviceToolsStorageHistoryMapper;
import com.ruoyi.system.domain.TZhgdDeviceToolsStorageHistory;
import com.ruoyi.system.service.ITZhgdDeviceToolsStorageHistoryService;
import com.ruoyi.common.core.text.Convert;

/**
 * 工器具使用记录Service业务层处理
 * 
 * @author wuyafeng
 * @date 2025-01-16
 */
@Service
public class TZhgdDeviceToolsStorageHistoryServiceImpl implements ITZhgdDeviceToolsStorageHistoryService 
{
    private static final Logger log = LoggerFactory.getLogger(TZhgdDeviceToolsStorageHistoryServiceImpl.class);
    @Autowired
    private TZhgdDeviceToolsStorageHistoryMapper tZhgdDeviceToolsStorageHistoryMapper;
    @Autowired
    private TZhgdDeviceToolsStorageMapper storageMapper;

    /**
     * 查询工器具使用记录
     *
     * @param id 工器具使用记录主键
     * @return 工器具使用记录
     */
    @Override
    public TZhgdDeviceToolsStorageHistory selectTZhgdDeviceToolsStorageHistoryById(String id)
    {
        return tZhgdDeviceToolsStorageHistoryMapper.selectTZhgdDeviceToolsStorageHistoryById(id);
    }

    /**
     * 查询工器具使用记录列表
     * 
     * @param tZhgdDeviceToolsStorageHistory 工器具使用记录
     * @return 工器具使用记录
     */
    @Override
    public List<TZhgdDeviceToolsStorageHistory> selectTZhgdDeviceToolsStorageHistoryList(TZhgdDeviceToolsStorageHistory tZhgdDeviceToolsStorageHistory)
    {
        return tZhgdDeviceToolsStorageHistoryMapper.selectTZhgdDeviceToolsStorageHistoryList(tZhgdDeviceToolsStorageHistory);
    }

    /**
     * 新增工器具使用记录
     * 
     * @param tZhgdDeviceToolsStorageHistory 工器具使用记录
     * @return 结果
     */
    @Override
    public AjaxResult insertTZhgdDeviceToolsStorageHistory(TZhgdDeviceToolsStorageHistory tZhgdDeviceToolsStorageHistory)
    {
        //先判断rfid编码是否存在
        int flag = tZhgdDeviceToolsStorageHistoryMapper.isFalg(tZhgdDeviceToolsStorageHistory.getRfid());
        if(flag >= 1){
            return AjaxResult.error();
        }

        TZhgdDeviceToolsStorage storage = new TZhgdDeviceToolsStorage();
        storage.setId(PlatformTools.get20UUID());
        storage.setRfid(tZhgdDeviceToolsStorageHistory.getRfid());
        storage.setCreateTime(DateUtils.getNowDate());
        storage.setUpdateTime(DateUtils.getNowDate());
        storage.setStatus(0);
        storage.setToolId(tZhgdDeviceToolsStorageHistory.getToolId());
        storage.setDeleteFlag(0);
        storageMapper.insertTZhgdDeviceToolsStorage(storage);

        tZhgdDeviceToolsStorageHistory.setId(PlatformTools.get20UUID());
        tZhgdDeviceToolsStorageHistory.setStorageId(storage.getId());
        tZhgdDeviceToolsStorageHistory.setStorageTypeCode("10");
        tZhgdDeviceToolsStorageHistory.setUserName("杨旭");
        tZhgdDeviceToolsStorageHistory.setCreateTime(DateUtils.getNowDate());
        tZhgdDeviceToolsStorageHistory.setUpdateTime(DateUtils.getNowDate());
        tZhgdDeviceToolsStorageHistory.setDeleteFlag(0);
        tZhgdDeviceToolsStorageHistoryMapper.insertTZhgdDeviceToolsStorageHistory(tZhgdDeviceToolsStorageHistory);
        return AjaxResult.success();

    }

    @Async
    @Override
    public void savaHistory(String epc, TZhgdPersonAttnH personAttnH){
        log.info("获取扫描编号EPC:"+epc);
        TZhgdDeviceToolsStorage tZhgdDeviceToolsStorage = storageMapper.selectToolsStorageByRfid(epc);
        log.info("工器具信息:"+tZhgdDeviceToolsStorage);
        if(tZhgdDeviceToolsStorage ==null ||tZhgdDeviceToolsStorage.getId() == null){//标签未录入，无法入库、出库
            log.error("【"+epc+"】标签未录入，无法入库/出库！");
        }else {
            Date nowDate = DateUtils.getNowDate();
            TZhgdDeviceToolsStorageHistory history = new TZhgdDeviceToolsStorageHistory();
            history.setId(PlatformTools.get20UUID());
            history.setStorageId(tZhgdDeviceToolsStorage.getId());
            history.setToolId(tZhgdDeviceToolsStorage.getToolId());
            history.setIdCard(personAttnH.getIdCard());
            history.setUserName(personAttnH.getName());
            history.setCreateTime(nowDate);
            history.setUpdateTime(nowDate);
            tZhgdDeviceToolsStorage.setUpdateTime(nowDate);
            if(tZhgdDeviceToolsStorage.getStatus() == 0){//在库  执行领用操作
                history.setStorageTypeCode("20");
                tZhgdDeviceToolsStorage.setStatus(1);
            }else if(tZhgdDeviceToolsStorage.getStatus() == 1){//不在库  执行归还操作
                history.setStorageTypeCode("30");
                tZhgdDeviceToolsStorage.setStatus(0);
            }
            tZhgdDeviceToolsStorageHistoryMapper.insertTZhgdDeviceToolsStorageHistory(history);
            this.updateTZhgdDeviceToolsStorageHistory(tZhgdDeviceToolsStorage);
        }
    }

    /**
     * 修改工器具使用记录
     * 
     * @return 结果
     */
    @Override
    public AjaxResult updateTZhgdDeviceToolsStorageHistory(TZhgdDeviceToolsStorage storage)
    {
        //先判断rfid编码是否存在
        int flag = tZhgdDeviceToolsStorageHistoryMapper.isFalgById(storage);
        if(flag >= 1){
            return AjaxResult.error();
        }
        storage.setUpdateTime(DateUtils.getNowDate());
        storageMapper.updateTZhgdDeviceToolsStorage(storage);
        return AjaxResult.success();
    }

    /**
     * 批量删除工器具使用记录
     * 
     * @param ids 需要删除的工器具使用记录主键
     * @return 结果
     */
    @Override
    public int deleteTZhgdDeviceToolsStorageHistoryByIds(String ids)
    {
        return tZhgdDeviceToolsStorageHistoryMapper.deleteTZhgdDeviceToolsStorageHistoryByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除工器具使用记录信息
     * 
     * @param id 工器具使用记录主键
     * @return 结果
     */
    @Override
    public int deleteTZhgdDeviceToolsStorageHistoryById(String id)
    {
        return tZhgdDeviceToolsStorageHistoryMapper.deleteTZhgdDeviceToolsStorageHistoryById(id);
    }

    @Override
    public List<TZhgdDeviceToolsInfo> findDropDownList(String toolTypeCode) {
        return tZhgdDeviceToolsStorageHistoryMapper.findDropDownList(toolTypeCode);
    }
    @Override
    public List<TZhgdDeviceToolsStorageHistory> toolsStorageHistoryNoSync() {
        return tZhgdDeviceToolsStorageHistoryMapper.selectToolsStorageHistoryNoSync();
    }

    @Async
    @Override
    public String uploadStorageHistory(String url,String projectId){
        List<TZhgdDeviceToolsStorageHistory> storageHistory = toolsStorageHistoryNoSync();
        if(storageHistory==null||storageHistory.size()==0){
            log.info("storageHistory no data to upload...");
            return "storageHistory no data  to upload...";
        }
        storageHistory.forEach(x -> {
            x.setProjectId(projectId);
        });
        JSONObject obj = new JSONObject();
        obj.put("storageHistory",storageHistory);
        try {
            String result = HttpUtils.postCall(url, obj.toString());
            JSONObject jsonData = JSONObject.parseObject(result);
            if("success".equals(jsonData.get("state"))){
                storageHistory.forEach( toolsStorageHistory->{
                    toolsStorageHistory.setSyncFlag(1);
                    tZhgdDeviceToolsStorageHistoryMapper.updateTZhgdDeviceToolsStorageHistory(toolsStorageHistory);
                });
            }
            log.info("请求结果"+result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return "工器具类型同步任务执行";
    }

}
